<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <template #header>
      <el-row :gutter="20">
        <el-col :span="12">库存管理</el-col>
        <el-col :span="12" class="text-right">
            <el-button type="primary" @click="showAddDrawer">添加库存</el-button>
          
        </el-col>
      </el-row>
    </template>

    <!-- 搜索栏 -->
    <div>
      <el-table :data="articles" v-loading="loading" style="width: 100%">
        <el-table-column fixed label="ID" prop="id" width="80"></el-table-column>
        <el-table-column label="仓库ID" prop="warehouse_id" width="120"></el-table-column>
        <el-table-column label="物品ID" prop="item_id" width="120"></el-table-column>
        <el-table-column label="数量" prop="quantity" width="100"></el-table-column>
        <el-table-column label="状态" prop="status" width="120"></el-table-column>
        <el-table-column label="创建者ID" prop="created_by" width="120"></el-table-column>
        <el-table-column label="创建时间" prop="created_at" width="180"></el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="{ row }">
            <!-- 根据用户角色动态显示按钮 -->
            <template v-if="isAuditor">
              <el-button type="primary" size="small" @click="showApproveDialog(row)">审批</el-button>
            </template>
            <template v-else>
              <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
            </template>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 文章发表抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="50%" direction="rtl">
      <AddArticleSet v-if="dialogType === 'add'" @cancel="handleCancel" />
      <EditArticleSet v-if="dialogType === 'edit'" :articleData="currentArticle" @cancel="handleCancel" />
    </el-drawer>
    <!-- 审批对话框 -->
    <el-dialog v-model="approveDialogVisible" title="库存审批">
      <el-form :model="approveForm" label-width="100px">
        <el-form-item label="审核状态">
          <el-select v-model="approveForm.status" placeholder="请选择审核状态">
            <el-option label="通过" value="approved"></el-option>
            <el-option label="拒绝" value="rejected"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input v-model="approveForm.comment" type="textarea" placeholder="请输入审核备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApproval">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus';
import AddArticleSet from '@/views/Page/addArticleSet.vue';
import EditArticleSet from '@/views/Page/editArticleSet.vue';
import { getInventory, deleteInventory } from '@/api/inventory';
import { addAudit } from '@/api/audit';

// 从 localStorage 获取 user_info
const userInfo = ref(JSON.parse(localStorage.getItem('user_info')));
const isAuditor = computed(() => userInfo.value && ['audit', 'super'].includes(userInfo.value.role_type.toLowerCase()));

// 数据定义
const articles = ref([]);
const categories = ref([]);
const loading = ref(false);
const drawerVisible = ref(false);
const dialogType = ref('add');
const currentArticle = ref(null);
const currentPage = ref(1);
const totalArticles = ref(0);
const approveDialogVisible = ref(false);
const approveForm = ref({
  inventory_id: null,
  status: '',
  comment: ''
});

// 计算属性
const drawerTitle = computed(() => {
  return dialogType.value === 'add' ? '添加库存' : '编辑库存';
});

// 方法定义
const fetchArticles = async () => {
  loading.value = true;
  try {
    const res = await getInventory();
    console.log('getInventory', res);
    const { code, message } = res.data
    console.log('code,message :>> ', code, message);
    if (code === 200) {
      articles.value = res.data.inventories;
      console.log("articles", articles.value);

      ElMessage.success(message);
    } else {
      ElMessage.error(message || '获取库存列表失败');
    }
  } catch (error) {
    ElMessage.error('获取库存列表失败：' + error.message);
  } finally {
    loading.value = false;
  }
};



const showAddDrawer = () => {
  dialogType.value = 'add';
  drawerVisible.value = true;
};

const handleEdit = (row) => {
  dialogType.value = 'edit';
  drawerVisible.value = true;
  currentArticle.value = { ...row };
  console.log('currentArticle', row);

};

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const { data } = await deleteInventory({ id: row.id });
      if (data.code === 200) {
        ElMessage.success('删除成功');
        fetchArticles();
      } else {
        ElMessage.error(data.message || '删除失败');
      }
    } catch (error) {
      ElMessage.error('删除失败：' + error.message);
    }
  }).catch(() => { });
};

const closeDrawer = () => {
  drawerVisible.value = false;
  currentArticle.value = null;
};

const handleCancel = () => {
  closeDrawer();
  fetchArticles();

};

// 生命周期钩子
onMounted(() => {
  fetchArticles();
});
// 显示审批对话框
const showApproveDialog = (row) => {
  approveForm.value.inventory_id = row.id;
  approveForm.value.status = '';
  approveForm.value.comment = '';
  approveDialogVisible.value = true;
};

// 提交审批信息
const submitApproval = async () => {
  try {
    const res = await addAudit(approveForm.value);
    if (res.data.code === 200) {
      ElMessage.success('审批成功');
      approveDialogVisible.value = false;
      fetchArticles();
    } else {
      ElMessage.error(res.data.message || '审批失败');
    }
  } catch (error) {
    ElMessage.error('审批失败：' + error.message);
  }
};
</script>

<style scoped>
.text-right {
  text-align: right;
}

.article-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>